<template>
  <div class="data-preprocessing-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>数据预处理</h2>
      <p class="subtitle">为ML.NET预测模型准备和清洗数据</p>
    </div>

    <!-- 数据源配置 -->
    <el-card class="data-source-config" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>数据源配置</span>
          <el-button type="primary" @click="loadDataSources" :loading="loading">
            加载数据源
          </el-button>
        </div>
      </template>

      <el-form :model="dataSourceConfig" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="历史出库数据">
              <el-select v-model="dataSourceConfig.outboundTable" placeholder="选择出库数据表">
                <el-option label="ShowEnterOut" value="ShowEnterOut" />
                <el-option label="OutboundHistory" value="OutboundHistory" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="库存数据">
              <el-select v-model="dataSourceConfig.stockTable" placeholder="选择库存数据表">
                <el-option label="ShowStock" value="ShowStock" />
                <el-option label="CurrentStock" value="CurrentStock" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品数据">
              <el-select v-model="dataSourceConfig.productTable" placeholder="选择产品数据表">
                <el-option label="Product" value="Product" />
                <el-option label="ProductInfo" value="ProductInfo" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="时间范围">
              <el-date-picker
                v-model="dataSourceConfig.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数据量限制">
              <el-input-number
                v-model="dataSourceConfig.limit"
                :min="100"
                :max="100000"
                placeholder="最大记录数"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 数据质量检查 -->
    <el-card class="data-quality-check" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>数据质量检查</span>
          <el-button type="warning" @click="checkDataQuality" :loading="checking">
            开始检查
          </el-button>
        </div>
      </template>

      <div v-if="qualityReport.length > 0" class="quality-report">
        <el-alert
          v-for="report in qualityReport"
          :key="report.id"
          :title="report.title"
          :type="report.type"
          :description="report.description"
          show-icon
          :closable="false"
          style="margin-bottom: 10px;"
        />
      </div>

      <div v-else class="quality-stats">
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-number">{{ dataStats.totalRecords }}</div>
              <div class="stat-label">总记录数</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-number">{{ dataStats.validRecords }}</div>
              <div class="stat-label">有效记录数</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-number">{{ dataStats.duplicateRecords }}</div>
              <div class="stat-label">重复记录数</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-number">{{ dataStats.missingRecords }}</div>
              <div class="stat-label">缺失记录数</div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 数据清洗规则 -->
    <el-card class="data-cleaning-rules" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>数据清洗规则</span>
          <el-button type="success" @click="applyCleaningRules" :loading="cleaning">
            应用清洗规则
          </el-button>
        </div>
      </template>

      <el-form :model="cleaningRules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="处理缺失值">
              <el-select v-model="cleaningRules.missingValueStrategy" placeholder="选择策略">
                <el-option label="删除记录" value="delete" />
                <el-option label="填充平均值" value="mean" />
                <el-option label="填充中位数" value="median" />
                <el-option label="填充0" value="zero" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="处理异常值">
              <el-select v-model="cleaningRules.outlierStrategy" placeholder="选择策略">
                <el-option label="保留" value="keep" />
                <el-option label="删除" value="delete" />
                <el-option label="限制范围" value="limit" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="处理重复值">
              <el-select v-model="cleaningRules.duplicateStrategy" placeholder="选择策略">
                <el-option label="保留第一条" value="first" />
                <el-option label="保留最后一条" value="last" />
                <el-option label="删除所有" value="delete" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="数量范围限制">
              <el-input
                v-model="cleaningRules.quantityRange"
                placeholder="最小值,最大值 (如: 0,10000)"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="价格范围限制">
              <el-input
                v-model="cleaningRules.priceRange"
                placeholder="最小值,最大值 (如: 0,1000000)"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="数据标准化">
          <el-checkbox-group v-model="cleaningRules.normalization">
            <el-checkbox label="数量标准化" value="quantity" />
            <el-checkbox label="价格标准化" value="price" />
            <el-checkbox label="时间标准化" value="time" />
          </el-checkbox-group>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 特征工程 -->
    <el-card class="feature-engineering" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>特征工程</span>
          <el-button type="primary" @click="generateFeatures" :loading="generating">
            生成特征
          </el-button>
        </div>
      </template>

      <el-form :model="featureConfig" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="时间特征">
              <el-checkbox-group v-model="featureConfig.timeFeatures">
                <el-checkbox label="月份" value="month" />
                <el-checkbox label="季度" value="quarter" />
                <el-checkbox label="星期" value="weekday" />
                <el-checkbox label="是否节假日" value="holiday" />
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品特征">
              <el-checkbox-group v-model="featureConfig.productFeatures">
                <el-checkbox label="产品类别" value="category" />
                <el-checkbox label="产品规格" value="specification" />
                <el-checkbox label="产品价格等级" value="priceLevel" />
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="统计特征">
              <el-checkbox-group v-model="featureConfig.statisticalFeatures">
                <el-checkbox label="移动平均" value="movingAverage" />
                <el-checkbox label="趋势指标" value="trend" />
                <el-checkbox label="季节性指标" value="seasonality" />
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="特征选择">
          <el-select
            v-model="featureConfig.selectedFeatures"
            multiple
            placeholder="选择要使用的特征"
            style="width: 100%"
          >
            <el-option label="历史出库量" value="historicalQuantity" />
            <el-option label="当前库存" value="currentStock" />
            <el-option label="产品价格" value="productPrice" />
            <el-option label="月份" value="month" />
            <el-option label="季度" value="quarter" />
            <el-option label="产品类别" value="category" />
            <el-option label="移动平均" value="movingAverage" />
            <el-option label="趋势指标" value="trend" />
          </el-select>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据预览 -->
    <el-card class="data-preview" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>数据预览</span>
          <div class="header-actions">
            <el-button @click="refreshPreview">刷新</el-button>
            <el-button type="success" @click="exportProcessedData">导出数据</el-button>
          </div>
        </div>
      </template>

      <el-table :data="previewData" border style="width: 100%" max-height="400">
        <el-table-column prop="date" label="日期" width="120" />
        <el-table-column prop="productCode" label="产品编码" width="120" />
        <el-table-column prop="productName" label="产品名称" width="150" />
        <el-table-column prop="quantity" label="出库数量" width="100" />
        <el-table-column prop="price" label="单价" width="100" />
        <el-table-column prop="category" label="产品类别" width="100" />
        <el-table-column prop="month" label="月份" width="80" />
        <el-table-column prop="quarter" label="季度" width="80" />
        <el-table-column prop="movingAverage" label="移动平均" width="100" />
        <el-table-column prop="trend" label="趋势" width="80" />
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="previewPagination.page"
          v-model:page-size="previewPagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="previewPagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handlePreviewSizeChange"
          @current-change="handlePreviewPageChange"
        />
      </div>
    </el-card>

    <!-- 处理进度 -->
    <el-card class="processing-progress" shadow="hover" v-if="processing">
      <template #header>
        <span>处理进度</span>
      </template>

      <el-progress
        :percentage="progressPercentage"
        :status="progressStatus"
        :stroke-width="20"
      />
      <div class="progress-info">
        <p>当前步骤: {{ currentStep }}</p>
        <p>已处理记录: {{ processedRecords }} / {{ totalRecords }}</p>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import http from '@/http/axiosHelper'
// 数据源配置
const dataSourceConfig = reactive({
  outboundTable: 'ShowEnterOut',
  stockTable: 'ShowStock',
  productTable: 'Product',
  dateRange: [],
  limit: 10000
})

// 数据清洗规则
const cleaningRules = reactive({
  missingValueStrategy: 'mean',
  outlierStrategy: 'limit',
  duplicateStrategy: 'first',
  quantityRange: '0,10000',
  priceRange: '0,1000000',
  normalization: ['quantity', 'price']
})

// 特征工程配置
const featureConfig = reactive({
  timeFeatures: ['month', 'quarter'],
  productFeatures: ['category', 'priceLevel'],
  statisticalFeatures: ['movingAverage', 'trend'],
  selectedFeatures: ['historicalQuantity', 'currentStock', 'month', 'category']
})

// 状态变量
const loading = ref(false)
const checking = ref(false)
const cleaning = ref(false)
const generating = ref(false)
const processing = ref(false)

// 数据统计
const dataStats = reactive({
  totalRecords: 0,
  validRecords: 0,
  duplicateRecords: 0,
  missingRecords: 0
})

// 质量报告
interface QualityReport {
  id: number
  title: string
  type: string
  description: string
  severity: string
  count: number
}

const qualityReport = ref<QualityReport[]>([])

// 预览数据
const previewData = ref([])
const previewPagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 处理进度
const progressPercentage = ref(0)
const progressStatus = ref('')
const currentStep = ref('')
const processedRecords = ref(0)
const totalRecords = ref(0)

// 加载数据源
const loadDataSources = async () => {
  loading.value = true
  try {
    const response = await axios.post('/api/MLNet/LoadDataSources', dataSourceConfig)
    if (response.data.code === 200) {
      ElMessage.success('数据源加载成功')
      updateDataStats(response.data.data)
    } else {
      ElMessage.error(response.data.message || '数据源加载失败')
    }
  } catch (error) {
    console.error('加载数据源失败:', error)
    ElMessage.error('加载数据源时发生错误')
  } finally {
    loading.value = false
  }
}

// 检查数据质量
const checkDataQuality = async () => {
  checking.value = true
  try {
    const response = await axios.get('/api/MLNet/CheckDataQuality', {
      params: dataSourceConfig
    })
    if (response.data.code === 200) {
      qualityReport.value = response.data.data.issues || []
      updateDataStats(response.data.data.stats)
      ElMessage.success('数据质量检查完成')
    } else {
      ElMessage.error(response.data.message || '数据质量检查失败')
    }
  } catch (error) {
    console.error('数据质量检查失败:', error)
    ElMessage.error('数据质量检查时发生错误')
  } finally {
    checking.value = false
  }
}

// 应用清洗规则
const applyCleaningRules = async () => {
  cleaning.value = true
  processing.value = true
  currentStep.value = '应用数据清洗规则'
  
  try {
    const response = await axios.post('/api/MLNet/ApplyCleaningRules', {
      rules: cleaningRules,
      config: dataSourceConfig
    })
    
    if (response.data.code === 200) {
      progressPercentage.value = 100
      progressStatus.value = 'success'
      ElMessage.success('数据清洗完成')
      updateDataStats(response.data.data.stats)
    } else {
      progressStatus.value = 'exception'
      ElMessage.error(response.data.message || '数据清洗失败')
    }
  } catch (error) {
    console.error('数据清洗失败:', error)
    progressStatus.value = 'exception'
    ElMessage.error('数据清洗时发生错误')
  } finally {
    cleaning.value = false
    setTimeout(() => {
      processing.value = false
      progressPercentage.value = 0
    }, 2000)
  }
}

// 生成特征
const generateFeatures = async () => {
  generating.value = true
  processing.value = true
  currentStep.value = '生成特征工程'
  
  try {
    const response = await axios.post('/api/MLNet/GenerateFeatures', {
      features: featureConfig,
      config: dataSourceConfig
    })
    
    if (response.data.code === 200) {
      progressPercentage.value = 100
      progressStatus.value = 'success'
      ElMessage.success('特征生成完成')
      loadPreviewData()
    } else {
      progressStatus.value = 'exception'
      ElMessage.error(response.data.message || '特征生成失败')
    }
  } catch (error) {
    console.error('特征生成失败:', error)
    progressStatus.value = 'exception'
    ElMessage.error('特征生成时发生错误')
  } finally {
    generating.value = false
    setTimeout(() => {
      processing.value = false
      progressPercentage.value = 0
    }, 2000)
  }
}

// 加载预览数据
const loadPreviewData = async () => {
  try {
    const response = await axios.get('/api/MLNet/GetPreviewData', {
      params: {
        page: previewPagination.page,
        size: previewPagination.size
      }
    })
    
    if (response.data.code === 200) {
      previewData.value = response.data.data.items || []
      previewPagination.total = response.data.data.total || 0
    }
  } catch (error) {
    console.error('加载预览数据失败:', error)
  }
}

// 刷新预览
const refreshPreview = () => {
  loadPreviewData()
}

// 导出处理后的数据
const exportProcessedData = () => {
  ElMessage.success('数据导出功能开发中...')
}

// 更新数据统计
const updateDataStats = (stats: any) => {
  Object.assign(dataStats, stats)
}

// 分页处理
const handlePreviewSizeChange = (size: number) => {
  previewPagination.size = size
  previewPagination.page = 1
  loadPreviewData()
}

const handlePreviewPageChange = (page: number) => {
  previewPagination.page = page
  loadPreviewData()
}

onMounted(() => {
  // 初始化时加载数据统计
  checkDataQuality()
})
</script>

<style scoped>
.data-preprocessing-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-header h2 {
  color: #303133;
  margin-bottom: 10px;
}

.subtitle {
  color: #909399;
  font-size: 14px;
}

.data-source-config,
.data-quality-check,
.data-cleaning-rules,
.feature-engineering,
.data-preview,
.processing-progress {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.quality-report {
  margin-bottom: 20px;
}

.quality-stats {
  padding: 20px 0;
}

.stat-item {
  text-align: center;
  padding: 20px;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 10px;
}

.stat-label {
  color: #909399;
  font-size: 14px;
}

.pagination-container {
  margin-top: 20px;
  text-align: center;
}

.progress-info {
  margin-top: 15px;
  text-align: center;
}

.progress-info p {
  margin: 5px 0;
  color: #606266;
}
</style> 